package com.data.mv.sql;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class SqlInsertTable {
    public static String insert(String tableName, List<String> cols, List<Map<String, Object>> data) {
        StringBuilder sql = new StringBuilder("insert into ").append(tableName).append(" ");
        sql.append("(");
        cols.stream().forEach(c->{
            sql.append("`");
            sql.append(c);
            sql.append("`");
            sql.append(",");
        });
        sql.deleteCharAt(sql.length() - 1);
        sql.append(")");
        sql.append("values");
        data.stream().forEach(d -> {
            sql.append("(");
            cols.stream().forEach(c -> {
                if (checkDataType(d.get(c))) {
                    sql.append("'");
                }

                sql.append(Objects.nonNull(d.get(c))&&d.get(c) instanceof String?escapeStr(d.get(c).toString()):d.get(c));

                if (checkDataType(d.get(c))) {
                    sql.append("'");
                }
                sql.append(",");
            });
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
            sql.append(",");
        });
        sql.deleteCharAt(sql.length() - 1);
        return sql.toString();
    }

    private static boolean checkDataType(Object o) {
        if (Objects.isNull(o)) {
            return false;
        }
        if (o instanceof Integer) {
            return false;
        }
        if (o instanceof BigDecimal) {
            return false;
        }
        if (o instanceof Float) {
            return false;
        }
        if (o instanceof Double) {
            return false;
        }
        return true;
    }

    private static String escapeStr(String s) {
        return s.replaceAll("\'", "\\\\'").replaceAll("\"","\\\\\"");
    }
}
